<template>
   <div>
      <div style="display: flex; justify-content: space-between">
         <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-top: 12px; margin-left: 32px"
         >
            <el-breadcrumb-item style="font-size: 16px"
               >系统管理</el-breadcrumb-item
            >
            <el-breadcrumb-item>
               <span style="color: #409eff; font-size: 16px">用户管理</span>
            </el-breadcrumb-item>
         </el-breadcrumb>
      </div>

      <div class="search_container">
         <div class="search_container_item">
            <div style="display: flex; flex: 2; margin-right: 20px">
               <span>姓名</span>
               <el-input
                  v-model="searchConditions.name"
                  class="search_input"
                  placeholder="要查询的姓名"
               />
            </div>
            <div style="display: flex; flex: 3; margin-right: 20px">
               <span style="flex: 2">学号/学工号</span>
               <el-input
                  style="flex: 3"
                  v-model="searchConditions.stuId"
                  class="search_input"
                  placeholder="要查询的学号/学工号"
               />
            </div>
            <div style="display: flex; flex: 3">
               <span style="flex: 2">担任角色</span>
               <el-select
                  v-model="searchConditions.roleId"
                  placeholder="请选择角色"
                  style="flex: 3; height: 28px"
               >
                  <el-option
                     v-for="role in systemRoles"
                     :key="role.id"
                     :label="role.roleName"
                     :value="role.id"
                  ></el-option>
               </el-select>
            </div>
         </div>
         <el-divider style="margin: 13px 0"></el-divider>
         <div class="search_container_button">
            <el-button
               style="width: 80px; height: 30px; margin-right: 30px"
               type="primary"
               @click="searchUserByConditions()"
               >查询</el-button
            >
            <el-button
               style="width: 80px; height: 30px"
               type="info"
               @click="resetSearch()"
               >重置</el-button
            >
         </div>
      </div>

      <!-- 用户列表 -->
      <div>
         <el-table
            style="border-radius: 10px"
            :data="userPageInfo.userList"
            stripe
            :header-cell-style="{ height: '60px', fontSize: '16px' }"
            :row-class-name="disabledUserTableClassName"
            :cell-style="{ height: '60px', fontSize: '14px' }"
            :default-expand-all="false"
         >
            <el-table-column
               prop="num"
               label="序号"
               header-align="center"
               min-width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="name"
               label="用户姓名"
               header-align="center"
               min-width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="stuId"
               label="学号/学工号"
               header-align="center"
               min-width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="email"
               label="邮箱"
               header-align="center"
               min-width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="telephone"
               label="联系电话"
               header-align="center"
               min-width="100"
               align="center"
            >
            </el-table-column>
            <el-table-column
               prop="roles"
               label="担任角色"
               header-align="center"
               min-width="100"
               align="center"
            >
               <template #default="{ row }">
                  <ul class="array-list">
                     <li
                        v-for="item in row.roles"
                        :key="item"
                        class="array-item"
                     >
                        {{ item.roleName }}
                     </li>
                  </ul>
               </template>
            </el-table-column>
            <el-table-column
               label="用户权限"
               header-align="center"
               min-width="100"
               align="center"
               v-if="currentPagePermissionStatusByCurrentUser.assignPermission"
            >
               <template v-slot="scope">
                  <el-button
                     link
                     size="small"
                     style="color: #63a1f8; font-weight: 600"
                     @click="editUserPermissionDialogOpen(scope.row)"
                     >分配权限</el-button
                  >
               </template>
            </el-table-column>
            <el-table-column
               label="操作"
               width="240px"
               header-align="center"
               min-width="100"
               align="center"
               v-if="currentPagePermissionStatusByCurrentUser.operateUserList"
            >
               <template v-slot="scope">
                  <el-tooltip
                     v-if="scope.row.accState"
                     effect="dark"
                     placement="top-start"
                     content="编辑用户信息"
                  >
                     <el-icon
                        @click="editUserInfoButtonClick(scope.row)"
                        style="
                           font-size: 21px;
                           color: #5a9cf8;
                           margin-right: 10px;
                           cursor: pointer;
                        "
                     >
                        <Edit />
                     </el-icon>
                  </el-tooltip>
                  <el-tooltip
                     v-if="scope.row.accState"
                     effect="dark"
                     content="初始化用户密码"
                     placement="top-start"
                  >
                     <el-icon
                        @click="resetUserPassword(scope.row)"
                        style="
                           font-size: 21px;
                           color: #5a9cf8;
                           margin-right: 10px;
                           cursor: pointer;
                        "
                        ><Clock
                     /></el-icon>
                  </el-tooltip>
                  <el-tooltip
                     v-if="scope.row.accState"
                     effect="dark"
                     content="禁用此用户"
                     placement="top-start"
                  >
                     <el-icon
                        @click="forbiddenUserAccount(scope.row)"
                        style="font-size: 21px; color: #5a9cf8; cursor: pointer"
                        ><CircleClose
                     /></el-icon>
                  </el-tooltip>

                  <el-tooltip
                     v-if="!scope.row.accState"
                     effect="dark"
                     content="启用此用户"
                     placement="top-start"
                  >
                     <el-icon
                        @click="enableUserAccount(scope.row)"
                        style="font-size: 21px; color: #5a9cf8; cursor: pointer"
                        ><CircleCheck
                     /></el-icon>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>

         <!-- 分页 -->
         <div
            v-show="!showSearchResult"
            style="display: inline-block; margin-top: 30px; text-align: center"
         >
            <el-pagination
               @current-change="getUserListPage"
               :current-page="userPageInfo.currentPage"
               :page-sizes="[5, 10, 20, 30, 40]"
               @size-change="pageSizeChange"
               :page-size="userPageInfo.pageSize"
               layout="total, sizes, prev, pager, next, jumper"
               :total="userPageInfo.totalItemsNum"
            >
            </el-pagination>
         </div>
      </div>

      <!-- 分配权限 -->
      <el-dialog
         v-model="editUserPermissionDialogShow"
         width="1100px"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px; float: left"
               >{{ currentUserRoleAndPermission.userName }}-权限修改</span
            >
         </template>

         <div style="height: 100%; width: 100%">
            <el-divider content-position="left">角色列表</el-divider>

            <!-- 角色多选框 -->
            <div style="margin-left: 50px; text-align: left">
               <div>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.roles"
                  >
                     <el-checkbox
                        v-for="role of systemRoles"
                        :label="role"
                        :key="role"
                        style="margin-top: 10px; width: 200px"
                        >{{ role.roleName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>
            </div>

            <el-divider content-position="left">权限列表</el-divider>

            <!-- 权限多选框 -->
            <div style="margin-left: 50px; text-align: left">
               <div>
                  <span>系统管理</span>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">用户管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-用户管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">角色管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-角色管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">权限管理</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-权限管理'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>

                  <div style="margin: 15px 0"></div>
                  <span style="margin-left: 15px">操作日志</span>

                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '系统管理-操作日志'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>生源地图</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '生源地图'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>学生数据信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '学生数据信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>学院招生信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '学院招生信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>

               <div style="margin: 15px 0"></div>

               <div>
                  <span>招生省份信息</span>
                  <el-checkbox-group
                     style="margin-left: 30px"
                     v-model="currentUserRoleAndPermission.permissions"
                  >
                     <el-checkbox
                        v-for="permission of systemPermissions.filter(
                           (permission) =>
                              permission.permissionLevel === '招生省份信息'
                        )"
                        :label="permission"
                        :key="permission"
                        style="margin-top: 10px; width: 200px"
                        >{{ permission.permissionName }}
                     </el-checkbox>
                  </el-checkbox-group>
               </div>
            </div>
         </div>

         <template #footer>
            <el-button @click="editUserPermissionDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="confimChangeUserPermission()"
               >确 定</el-button
            >
            <div>
               <span style="color: red; font-size: 10px"
                  >如果修改的是当前登录用户的权限-自己的权限，确认修改后需重新登录，系统会自动跳转登录页面</span
               >
            </div>
         </template>
      </el-dialog>

      <!-- 个人信息编辑弹窗 -->
      <el-dialog v-model="personalInfoEditDialogShow" width="600px">
         <template #header>
            <h3 style="text-align: left">
               {{ userInfoEditForm.originName }}-个人信息修改:
            </h3>
         </template>

         <el-form
            ref="editUserInfoDom"
            :model="userInfoEditForm"
            :rules="editUserInfoRules"
         >
            <el-form-item label="姓名" label-width="100" prop="name">
               <el-input
                  v-model="userInfoEditForm.name"
                  style="width: 380px"
                  placeholder="请输入姓名："
               ></el-input>
            </el-form-item>

            <el-form-item label="联系电话" label-width="100" prop="telephone">
               <el-input
                  v-model="userInfoEditForm.telephone"
                  style="width: 380px"
                  placeholder="请输入联系电话："
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="personalInfoEditDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="editUserInfo()">修 改</el-button>
         </template>
      </el-dialog>
   </div>
</template>

<script>
import $axios from "@/axios";
import router from "@/rooter";
import { useStore } from "vuex";
import { onMounted, reactive, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
   name: "用户列表",
   setup() {
      const store = useStore();

      // 当前页当前用户权限
      let currentPagePermissionStatusByCurrentUser = reactive({
         userManagementPageShow: false,
         operateUserList: false,
         assignPermission: false,
      });

      // 用户分页信息
      let userPageInfo = reactive({
         userList: [],
         currentPage: 1,
         pageSize: 10,
         totalItemsNum: 0,
      });

      // 页面选择一页的条数
      function pageSizeChange(newSize) {
         userPageInfo.pageSize = newSize;
         // 回到第一页
         getUserListPage(1);
      }

      // 获取用户列表分页信息
      function getUserListPage(page) {
         userPageInfo.currentPage = page;
         showSearchResult.value = false;

         $axios
            .get(
               "/user/listUsers/" +
                  userPageInfo.currentPage +
                  "/" +
                  userPageInfo.pageSize
            )
            .then((resp) => {
               // 给item添加序号
               for (let i = 0; i < resp.data.data.records.length; i++) {
                  resp.data.data.records[i].num =
                     (resp.data.data.current - 1) * resp.data.data.size + i + 1;
               }

               // 赋值
               userPageInfo.userList = resp.data.data.records;
               userPageInfo.currentPage = resp.data.data.current;
               userPageInfo.pageSize = resp.data.data.size;
               userPageInfo.totalItemsNum = resp.data.data.total;
            });
      }

      // ===============================

      // 控制编辑用户权限的dialog是否显示
      let editUserPermissionDialogShow = ref(false);

      // 系统所有角色
      let systemRoles = ref([]);

      // 系统所有权限
      let systemPermissions = ref([]);

      // 当前点击用户的角色和权限
      let currentUserRoleAndPermission = reactive({
         userId: "",
         userName: "",
         roles: [],
         permissions: [],
         originRoles: [],
         originPermissions: [],
      });

      // 编辑权限弹窗打开事件
      function editUserPermissionDialogOpen(row) {
         editUserPermissionDialogShow.value = true;

         // 获取用户的权限
         currentUserRoleAndPermission.userId = row.id;
         currentUserRoleAndPermission.userName = row.name;
         currentUserRoleAndPermission.roles = row.roles;
         currentUserRoleAndPermission.originRoles = row.roles;
         currentUserRoleAndPermission.permissions = row.permissions;
         currentUserRoleAndPermission.originPermissions = row.permissions;

         // 获取系统所有权限
         $axios.get("/permission/allPermissions").then((resp) => {
            systemPermissions.value = resp.data.data;
         });
      }

      // 确认修改角色权限
      function confimChangeUserPermission() {
         // 校验用户和权限是否发生了变化
         if (
            JSON.stringify(currentUserRoleAndPermission.originPermissions) ===
               JSON.stringify(currentUserRoleAndPermission.permissions) &&
            JSON.stringify(currentUserRoleAndPermission.originRoles) ===
               JSON.stringify(currentUserRoleAndPermission.roles)
         ) {
            ElMessage({
               type: "info",
               message: "未修改任何内容",
               duration: 1500,
            });
            return;
         }

         // 发送修改用户角色权限请求
         $axios
            .post(
               "/user/updateUserRoleAndPermissions",
               currentUserRoleAndPermission
            )
            .then(() => {
               ElMessage({
                  type: "success",
                  message: "用户权限修改成功",
                  duration: 1000,
               });

               // 如果修改的是当前登录用户的权限-自己的权限
               if (
                  currentUserRoleAndPermission.userId ==
                  store.state.currentLoginUser.id
               ) {
                  localStorage.removeItem("token");
               }

               setTimeout(() => {
                  window.location.reload();
               }, 1000);
            });
      }

      // 窗口关闭时候
      watch(editUserPermissionDialogShow, (newValue) => {
         if (!newValue) {
            currentUserRoleAndPermission.userId = "";
            currentUserRoleAndPermission.userName = "";
            currentUserRoleAndPermission.roles = [];
            currentUserRoleAndPermission.originRoles = [];
            currentUserRoleAndPermission.permissions = [];
            currentUserRoleAndPermission.originPermissions = [];
         }
      });

      // ===============================

      // 编辑用户表单dom
      let editUserInfoDom = ref(null);

      // 控制编辑个人信息显示弹窗是否显示
      let personalInfoEditDialogShow = ref(false);

      // 用户信息修改表单
      let userInfoEditForm = reactive({
         id: "",
         name: "",
         originName: "",
         telephone: "",
         originTelephone: "",
      });

      // 编辑用户信息按钮点击
      function editUserInfoButtonClick(row) {
         userInfoEditForm.id = row.id;
         userInfoEditForm.name = row.name;
         userInfoEditForm.originName = row.name;
         userInfoEditForm.telephone = row.telephone;
         userInfoEditForm.originTelephone = row.telephone;

         personalInfoEditDialogShow.value = true;
      }

      // 用户信息修改规则
      const editUserInfoRules = {
         name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
         telephone: [
            { required: true, message: "请输入联系电话", trigger: "blur" },
            {
               validator: (rule, value, callback) => {
                  const reg = /^[1][3-9][0-9]{9}$/;
                  if (value == "" || value == undefined || value == null) {
                     callback();
                  } else {
                     if (!reg.test(value) && value != "") {
                        callback(new Error("请输入正确的电话号码"));
                     } else {
                        callback();
                     }
                  }
               },
               required: true,
               trigger: "blur",
            },
         ],
      };

      // 用户信息修改
      function editUserInfo() {
         editUserInfoDom.value.validate((valid) => {
            if (valid) {
               // 判断修改信息表单是否有改变
               if (
                  userInfoEditForm.name == userInfoEditForm.originName &&
                  userInfoEditForm.telephone == userInfoEditForm.originTelephone
               ) {
                  ElMessage({
                     type: "warning",
                     message: "未更改任何内容",
                     duration: 1500,
                  });
                  return;
               }

               // 发送axios请求
               $axios
                  .put("/user/updateUserInfo", userInfoEditForm)
                  .then((resp) => {
                     ElMessage({
                        type: "success",
                        message: "修改成功",
                        duration: 1000,
                     });

                     setTimeout(() => {
                        window.location.reload();
                     }, 1000);
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请填写正确的信息",
                  duration: 1500,
               });
            }
         });
      }

      // ===============================

      // 重置密码
      function resetUserPassword(row) {
         ElMessageBox.confirm(
            "是否重置用户 ‘" + row.name + "’ 的密码",
            "警告",
            {
               confirmButtonText: "重置",
               cancelButtonText: "取消",
               type: "warning",
               draggable: true,
            }
         ).then(() => {
            // 如果重置的是当前登录用户的密码
            if (store.state.currentLoginUser.id === row.id) {
               ElMessage({
                  type: "error",
                  message: "无法重置当前操作者自身的密码，请到个人中心修改",
                  duration: 1500,
               });
               return;
            }

            // 发送重置密码请求
            let resetPasswordForm = {
               id: row.id,
               password: "123456",
            };

            $axios
               .put("/user/updateUserPassword", resetPasswordForm)
               .then(() => {
                  ElMessage({
                     type: "success",
                     message: "密码重置成功，默认密码为：‘123456’",
                     duration: 1500,
                  });
               });
         });
      }

      // 禁用账号
      function forbiddenUserAccount(row) {
         ElMessageBox.confirm("是否禁用用户 ‘" + row.name + "’ ", "警告", {
            confirmButtonText: "禁用",
            cancelButtonText: "取消",
            type: "warning",
            draggable: true,
         }).then(() => {
            // 如果禁用的是当前登录用户
            if (store.state.currentLoginUser.id === row.id) {
               ElMessage({
                  type: "error",
                  message: "无法禁用当前操作者",
                  duration: 1500,
               });
               return;
            }

            // 发送禁用账号请求
            $axios.get("/user/forbiddenAccount/" + row.id).then(() => {
               ElMessage({
                  type: "success",
                  message: "用户" + row.name + "被禁用",
                  duration: 1500,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 1000);
            });
         });
      }

      // 启用账号
      function enableUserAccount(row) {
         ElMessageBox.confirm("是否启用用户 ‘" + row.name + "’ ", "警告", {
            confirmButtonText: "启用",
            cancelButtonText: "取消",
            type: "warning",
            draggable: true,
         }).then(() => {
            // 如果启用的是当前登录用户
            if (store.state.currentLoginUser.id === row.id) {
               ElMessage({
                  type: "error",
                  message: "非法操作",
                  duration: 1500,
               });
               return;
            }

            // 发送启用账号请求
            $axios.get("/user/enableUserAccount/" + row.id).then(() => {
               ElMessage({
                  type: "success",
                  message: "用户" + row.name + "已被启用",
                  duration: 1500,
               });

               setTimeout(() => {
                  window.location.reload();
               }, 1000);
            });
         });
      }

      // 被禁用用户的css类
      const disabledUserTableClassName = function ({ row, rowIndex }) {
         if (row.accState === false) {
            return "warning-row";
         }
         return "";
      };

      // ===============================

      // 搜索表单
      let searchConditions = reactive({
         name: "",
         stuId: "",
         roleId: "",
      });

      // 重置搜索框
      function resetSearch() {
         searchConditions.name = "";
         searchConditions.stuId = "";
         searchConditions.roleId = "";
      }

      let showSearchResult = ref(false);

      // 根据条件搜索
      function searchUserByConditions() {
         // 空条件
         if (
            searchConditions.name === "" &&
            searchConditions.stuId === "" &&
            searchConditions.roleId === ""
         ) {
            getUserListPage(1);
            return;
         }

         // 获取符合条件的用户
         $axios
            .post("/user/listUsersByConditions", searchConditions)
            .then((resp) => {
               // 给item添加序号
               for (let i = 0; i < resp.data.data.length; i++) {
                  resp.data.data[i].num = i + 1;
               }

               userPageInfo.userList = resp.data.data;
               showSearchResult.value = true;
            });
      }

      // 监听角色变化，权限做出相应的变化
      watch(
         () => currentUserRoleAndPermission.roles,
         (newValue, oldValue) => {
            if (oldValue.length === newValue.length) {
               return;
            }

            // 遍历所有newValue中的角色，将角色中的权限赋值到currentUserRoleAndPermission.permissions中

            // 被增加的角色
            let newItems = newValue.filter((item) => !oldValue.includes(item));

            if (newItems.length !== 0) {
               // 增加角色
               // 将被增加的角色，增加角色应有的权限
               newItems.forEach((newItem) => {
                  let permissions = newItem.systemPermissions;

                  permissions.forEach((permission) => {
                     let flag = false;
                     currentUserRoleAndPermission.permissions.forEach(
                        (item) => {
                           if (item.id === permission.id) {
                              flag = true;
                              return;
                           }
                        }
                     );

                     if (!flag) {
                        currentUserRoleAndPermission.permissions.push(
                           permission
                        );
                     }
                  });
               });
            } else {
               // 减少角色
               // 被减少的角色
               let removedItems = oldValue.filter(
                  (item) => !newValue.includes(item)
               );

               let permissions = removedItems[0].systemPermissions;

               permissions.forEach((permission) => {
                  currentUserRoleAndPermission.permissions =
                     currentUserRoleAndPermission.permissions.filter(
                        (element) => {
                           return element.id !== permission.id;
                        }
                     );
               });
            }
         }
      );

      // 等待vuex中的userPermission准备好
      function waitForPermissions() {
         return new Promise((resolve) => {
            store.watch(
               () => store.state.currentLoginUser.permissions,
               (newValue) => {
                  // 权限：
                  // 1.用户列表操作
                  // 2.用户权限分配
                  if (newValue) {
                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/systemManagement/userManagement"
                        ) {
                           currentPagePermissionStatusByCurrentUser.userManagementPageShow = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/systemManagement/userManagement/operateUser"
                        ) {
                           currentPagePermissionStatusByCurrentUser.operateUserList = true;
                        }

                        if (
                           permission.permissionPath ===
                           "/systemManagement/userManagement/assignPermission"
                        ) {
                           currentPagePermissionStatusByCurrentUser.assignPermission = true;
                        }
                     });

                     // 将 Promise 状态改为已完成
                     resolve();
                  }
               },
               {
                  immediate: true, // 立即监听
               }
            );
         });
      }

      // 发送请求获取用户数据
      onMounted(async () => {
         await waitForPermissions();

         if (!currentPagePermissionStatusByCurrentUser.userManagementPageShow) {
            ElMessage({
               type: "error",
               message: "用户无权限",
               duration: 1500,
            });
            router.go(-1);
            return;
         }

         getUserListPage(1);

         // 获取系统所有角色
         $axios.get("/role/allRole").then((resp) => {
            systemRoles.value = resp.data.data;
         });
      });

      return {
         userPageInfo,
         pageSizeChange,
         getUserListPage,
         editUserPermissionDialogShow,
         systemRoles,
         systemPermissions,
         currentUserRoleAndPermission,
         editUserPermissionDialogOpen,
         confimChangeUserPermission,
         personalInfoEditDialogShow,
         userInfoEditForm,
         editUserInfoRules,
         editUserInfoDom,
         editUserInfo,
         editUserInfoButtonClick,
         resetUserPassword,
         forbiddenUserAccount,
         disabledUserTableClassName,
         enableUserAccount,
         searchConditions,
         resetSearch,
         searchUserByConditions,
         showSearchResult,
         currentPagePermissionStatusByCurrentUser,
      };
   },
};
</script>

<style scoped>
.array-list {
   display: flex;
   flex-wrap: wrap;
   justify-content: center;
   margin: 0;
   margin-left: 6px;
   padding: 0;
}

.array-item {
   list-style: none;
   margin-right: 6px;
   text-align: center;
}

.el-divider--vertical_userRowInfo {
   display: inline-block;
   width: 2px;
   height: 15em !important;
   margin-top: -28px;
   vertical-align: middle;
   position: relative;
}

.checkbox-group-class {
   margin-left: 30px;
}

.search_container {
   padding: 18px;
   background-color: #fff;
   border-radius: 10px;
   margin: 20px 0;
   font-size: 14px;
}

.search_container_item {
   width: 65%;
   display: flex;
}

.search_container_item span {
   flex: 1;
   margin-top: 5px;
   margin-right: 5px;
}

.search_container .search_input {
   flex: 3;
   height: 28px;
}

.search_container_button {
   display: flex;
   justify-content: flex-start;
   margin-left: 12px;
}
</style>

<style>
.el-table .warning-row td {
   color: red;
}

.select-trigger {
   line-height: 28px;
   height: 28px;
}

.el-input--suffix {
   height: 28px;
}
</style>